package com.hc.programming.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/16 20:27
 */
public class 哲学家进餐 {
    /**
     * 5把锁
     */
    private ReentrantLock[] locks = new ReentrantLock[]{new ReentrantLock(), new ReentrantLock(), new ReentrantLock(),
            new ReentrantLock(), new ReentrantLock()};

    public static void main(String[] args) {

    }

    // call the run() method of any runnable to execute its code
    public void wantsToEat(int philosopher,
                           Runnable pickLeftFork,
                           Runnable pickRightFork,
                           Runnable eat,
                           Runnable putLeftFork,
                           Runnable putRightFork) throws InterruptedException {
        int left = philosopher;
        int right = (philosopher + 1) % 5;
        if (philosopher % 2 == 0) {
            locks[right].lock();
            locks[left].lock();
            pickLeftFork.run();
            pickRightFork.run();
        } else {
            locks[left].lock();
            locks[right].lock();
            pickRightFork.run();
            pickLeftFork.run();
        }
        eat.run();
        putLeftFork.run();
        locks[left].unlock();
        putRightFork.run();
        locks[right].unlock();
    }
}
